let fs = require('fs');
var path = require('path');

/**工程目录 C:/Users/admin/Desktop/ModuleProject */
let ProjectPath = Editor.Project.path.replace(/\\/g, '/');
// let assetsPath = ProjectPath + '/assets';

const startTag = "// start >>>>>>";
const endTag = "// end >>>>>>";

let obj = {};

let findModuleType = (tsPath, startString) => {
    obj = {};

    let find = (path) => {
        let files = fs.readdirSync(path, 'utf-8');
        //找出所有符合的类型
        files
            //排出.meta文件
            .filter((file) => {
                return checkName(file);
            })
            .forEach((file) => {
                let dir = `${path}/${file}`;
                const stat = fs.statSync(dir);
                let moudleName = file.split('.')[0];
                if (stat.isDirectory()) {
                    // console.log(moudleName, dir, "为文件夹");
                    obj[moudleName] = {};
                    // readFileList(dir, moudleName, null);

                    let path1 = dir;
                    let files1 = fs.readdirSync(path1, 'utf-8');
                    //找出所有符合的类型
                    files1
                        //排出.meta文件
                        .filter((file1) => {
                            return checkName(file1);
                        })
                        .forEach((file1) => {
                            let dir1 = `${path1}/${file1}`;
                            const stat1 = fs.statSync(dir1);
                            let moudleName1 = file1.split('.')[0];
                            if (stat1.isDirectory()) {
                                // console.log(moudleName1, dir1, "为文件夹");
                                obj[moudleName][moudleName1] = {};
                                readFileList(dir1, `${moudleName}/${moudleName1}`);
                                // console.log("文件夹类型", moudleName1);
                            } else {
                                // console.log("不是文件夹，写入", `${moudleName},${moudleName1}:   ${moudleName}/${moudleName1}`);
                                obj[moudleName][moudleName1] = `${moudleName}/${moudleName1}`;
                            }
                        });

                } else {
                    // console.log("不是文件夹，写入", `key:${moudleName},val:${moudleName}`);
                    obj[moudleName] = moudleName;
                }
            });
    };

    let readFileList = (dir, urlName) => {
        let files = fs.readdirSync(dir, "utf-8");
        //排除.meta结尾的文件
        files = files.filter((file) => {
            return checkName(file);
        });
        files.forEach((item, index) => {
            var fullPath = path.join(dir, item);
            const stat = fs.statSync(fullPath);
            let name = item.split('.')[0];
            //是否为文件夹
            if (stat.isDirectory()) {
                readFileList(path.join(dir, item), `${urlName}/${name}`); // 递归读取文件
            } else {
                let arr = urlName.split("/");
                let url = urlName.replace(arr[0] + "/", "");
                // console.log(url, "/", name);
                obj[arr[0]][arr[1]][name] = `${url}/${name}`;
            }
        });
    }

    // find(ProjectPath + '/assets/resources');
    find(ProjectPath + '/assets/bundle');

    //过滤出满足对应路径格式的信息
    let newString = startString;
    for (let key of Object.keys(obj)) {
        let value = obj[key];
        // console.log(key, value);
        if (typeof value == "object") {
            newString += `\n \t\t${key}: {`;
            for (let k of Object.keys(value)) {
                let val = value[k];
                if (typeof val == "object") {
                    newString += `\n \t\t\t${k}: {`;
                    for (let k of Object.keys(val)) {
                        let v = val[k];
                        // console.log(k, v);
                        newString += `\n \t\t\t\t"${k}": '${v}', `;
                    }
                    newString += `\n \t\t\t},`;
                } else {
                    newString += `\n \t\t\t"${k}": "${val}",`;
                }
            }
            newString += `\n \t\t},`;
        } else {
            newString += `\n \t\t"${key}": "${value}",`;
        }

    }
    newString += '\n \t}';
    // console.log(obj);
    // console.log('newString', newString);

    //改变名字到路径的映射
    let fileStr = fs.readFileSync(tsPath, 'utf-8');
    // fileStr = ts.replace(new RegExp(`${startString}([^;]*)`, 'm'), newString);

    let index1 = fileStr.indexOf(startTag);
    let index2 = fileStr.indexOf(endTag);

    // if (index1 >= 0 && index2 >= 0) {
    let jsStr1 = fileStr.slice(0, index1);
    let jsStr2 = fileStr.slice(index2 + endTag.length);
    fileStr = jsStr1
        + startTag + `\n`
        + `\t` + newString
        + `\n\t` + endTag
        + jsStr2;
    fs.writeFileSync(tsPath, fileStr);
    // }

    console.log("生成路径映射成功");
}

let checkName = (file) => {
    //名字前不带$号 且 不为.meta结尾
    if (file.endsWith(".meta") || file.substr(0, 1) == "$") {
        return false;
    } else {
        return true;
    }
}

let updateType = () => {
    // findModuleType(`${ProjectPath}/assets/script/game/common/config/GameBundleConfig.ts`, 'BundleName: {');
    findModuleType(`${ProjectPath}/assets/script/game/common/bundle/BundleConfig.ts`, 'BundleName = {');
    // findModuleType(`${ProjectPath}/extensions/oops-plugin-framework/assets/core/common/bundle/GameBundleConfig.ts`, 'BundleName = {');
};

/**
 * @en Registration method for the main process of Extension
 * @zh 为扩展的主进程的注册方法
 */
export const methods: { [key: string]: (...any: any) => any } = {
    // console.log("加载成功");
    onMessage() {
        updateType();
    }
};

/**
 * @en Hooks triggered after extension loading is complete
 * @zh 扩展加载完成后触发的钩子
 */
export const load = function () { };

/**
 * @en Hooks triggered after extension uninstallation is complete
 * @zh 扩展卸载完成后触发的钩子
 */
export const unload = function () { };
